package com.conn.service.socket.codec;

/**
 * 
 */

import java.io.UnsupportedEncodingException;

import org.apache.mina.core.buffer.IoBuffer;

/**
 * @author lushouzhi
 * 
 */
public class ProtocolBuilder {

	private IoBuffer store = IoBuffer.allocate(64).setAutoExpand(true);

	public Object build() {
		IoBuffer ret = IoBuffer.allocate(store.position() + 4);
		store.flip().rewind();
		ret.putInt(store.remaining() + 4);
		ret.put(store);
		store.clear();
		return ret.flip();
	}
	
	public void clear(){
	}

	public void setCmd(short value){
		store.putShort(value);
	}
	
	public void set(byte value) {
		store.put(value);
	}

	public void setShort(short value) {
		store.putShort(value);
	}

	public void setInt(int value) {
		store.putInt(value);
	}

	public void setLong(long value) {
		store.putLong(value);
	}

	public void setString(String value) {
		try {
			byte[] arr = value.getBytes("utf-8");
			store.putShort((short) arr.length);
			store.put(arr);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public void setByteArray(byte[] value){
		short len=(short) value.length;
		store.putShort(len);
		store.put(value);
	}
	
	
	public void setShortArray(short []value){
		short len=(short)value.length;
		store.putShort(len);
		for(short val:value){
			store.putShort(val);
		}
	}
	
	public void setIntArray(int []value){
		short len=(short)value.length;
		store.putShort(len);
		for(int val:value){
			store.putInt(val);
		}
	}
	
	public void setLongArray(long [] value){
		short len=(short)value.length;
		store.putShort(len);
		for(long val:value){
			store.putLong(val);
		}
	}
	
	public void setStringArray(String []value){
		short len=(short)value.length;
		store.putShort(len);
		for(String val:value){
			setString(val);
		}
	}
}
